<?php

namespace App\Kuafu\WaiMai\Model;

use App\Kuafu\Base\Model\Traits\KfWaiMaiSplit;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Kuafu\Base\Model\BaseModel;

class WaiMaiCallbackLogModel extends BaseModel
{
    use HasFactory;
    use KfWaiMaiSplit;

    protected $connection = 'mysqlWaiMai';
    protected $table      = 'waimai_callback_logs'; //表名
    protected $primaryKey = 'id';
    public    $timestamps = false;
    protected $fillable   = [
        'sourceType',
        'orderId',
        'thirdShopId',
        'shopId',
        'route',
        'callType',
        'requestData',
        'responseData',
        'errMsg',
        'createdAt',
    ];

    const CALL_TYPE_DEFAULT = 0; // 默认
    const CALL_TYPE_PUSH    = 1; // 订单推送

    /**
     * 接口入参信息入库
     * @param int $sourceType
     * @param int $orderId
     * @param string $storeId
     * @param string $requestData
     * @return int
     */
    public static function addData(
        int $sourceType,
        int $orderId,
        string $thirdShopId,
        string $requestData,
        string $route,
        int $shopId
    ): int {
        $createdAt = time();

        if (strpos($route, '/api/pay/callback/elmWaiMai/push?type=10') !== false) {
            $callType = self::CALL_TYPE_PUSH;
        } elseif (strpos($route, '/api/pay/callback/elmWaiMai/push?type=217') !== false) {
            $callType = self::CALL_TYPE_PUSH;
        } elseif (strpos($route, '/api/pay/callback/mtWaiMai/pushOrder') !== false) {
            $callType = self::CALL_TYPE_PUSH;
        } else {
            $callType = self::CALL_TYPE_DEFAULT;
        }

        return self::suffix($shopId)
                   ->insertGetId(compact('sourceType', 'orderId', 'thirdShopId', 'requestData', 'createdAt', 'route', 'shopId', 'callType'));
    }

    /**
     * 更新接口返回信息
     * @param int $id
     * @param string $responseData
     * @return int
     */
    public static function updateResponseData(int $id, int $shopId, string $responseData, string $errMsg = ''): int
    {
        return self::suffix($shopId)->where('id', $id)->update(['responseData' => $responseData, 'errMsg' => $errMsg]);
    }

    /**
     * 获取订单的镜像数据
     * @param int $orderId
     * @return array
     */
    public static function getInitData(int $orderId, int $shopId = 0): array
    {
        if (!$shopId) {
            $shopId = WaiMaiOrderIdShopIdMappingModel::getShopId($orderId);
        }

        $data = WaiMaiCallbackLogModel::suffix($shopId)
                                      ->where('orderId', $orderId)
                                      ->where('callType', self::CALL_TYPE_PUSH)
                                      ->value('requestData');
        if (!$data) {
            return [];
        }

        return json_decode($data, true);
    }
}
